package kr.hkit.android_bookmgr.activity;

import java.util.Calendar;
import java.util.GregorianCalendar;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import kr.hkit.android_bookmgr.R;
import kr.hkit.android_bookmgr.DAO.BookDAO;
import kr.hkit.android_bookmgr.DTO.BookData;
import kr.hkit.android_bookmgr.util.ImageUtil;
import android.app.ActionBar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class BookMarkActivity extends Activity { //책갈피 메인 

	private BookDAO mBookMgr;
	private int mId, mTotalpage, mStatus, mCurrentpage, mImgtype;
	private String mName, mAuthor ,mStartdate, mEnddate, mPublisher, mBookimg;
	private SeekBar mSeek;
	private int pro;
	private TextView mProgressTv, mSeekTv;
	private String setDate;
	private TextView enddate;
	private int mYear, mMonth, mDay;
	private LinearLayout pangimg;
	private BookData book;
	private TextView startdate;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d("TEST", "MARK - onCreate()");

		setContentView(R.layout.bookmark_activity);
		
		ActionBar mActionBar = getActionBar();
		mActionBar.setDisplayHomeAsUpEnabled(true); 
		mActionBar.setHomeButtonEnabled(true);

		calendar();
		mBookMgr = BookDAO.getInstance(this);
		
		Bundle bundle = this.getIntent().getExtras();
		book = bundle.getParcelable("BOOK");
		
		//이미지 불러오기
		ImageUtil.imageLoader(BookMarkActivity.this);
		DisplayImageOptions options = ImageUtil.dispalyOptions();

		ImageView img = (ImageView) findViewById(R.id.bookmark_img);
		if (book.getImgtype()==0){ //직찍
			ImageLoader.getInstance().displayImage("file:///"+book.getBookimg(), img, options);
		}else if(book.getImgtype()==1){ //갤러리
			ImageLoader.getInstance().displayImage("content://media/"+book.getBookimg(), img, options);
		}else{ //검색
			ImageLoader.getInstance().displayImage(book.getBookimg(), img, options);
		}
		
		TextView name = (TextView)findViewById(R.id.bookmark_name);
		name.setText(book.getName());
		TextView author = (TextView)findViewById(R.id.bookmark_author);
		author.setText(book.getAuthor());
		TextView publisher = (TextView)findViewById(R.id.bookmark_publisher);
		publisher.setText(book.getPublisher());
		TextView totalpage = (TextView)findViewById(R.id.bookmark_totalpage);
		totalpage.setText(book.getTotalpage()+"");
		startdate = (TextView)findViewById(R.id.bookmark_startdate);
		/*if(book.getStatus()==1){
			startdate.setTextSize(15);
			startdate.setHint("수정페이지에서 \n시작일을 등록하세요");
		}else{*/
			startdate.setText(book.getStartdate());
		//}
			
		
		enddate = (TextView)findViewById(R.id.bookmark_enddate);
		enddate.setText(book.getEnddate());
		
		
		mSeek = (SeekBar) findViewById(R.id.bookmark_seekbar); //시크바
		mSeekTv = (TextView) findViewById(R.id.bookmark_seekbartext); //페이지테스트
		mProgressTv = (TextView) findViewById(R.id.bookmark_progresstext); //완독몇페이지
		mSeek.setMax(book.getTotalpage()); //total페이지
		mSeekTv.setText(book.getCurrentpage() + " / " + book.getTotalpage() + "페이지");  //페이지표시
		mSeek.setProgress(book.getCurrentpage()); //시크바표시 
		
		if ((book.getTotalpage()-book.getCurrentpage())!=0){
			mProgressTv.setText("완독까지 "+(book.getTotalpage()-book.getCurrentpage())+" 페이지 남았습니다.");
		}else{
			mProgressTv.setText("독서완료. 축하축하합니다!");
			pangimg = (LinearLayout) findViewById(R.id.bookmark_pangimglinear);
			pangimg.setVisibility(LinearLayout.VISIBLE);
		}
		
		mSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
			
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				
			}
			
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) { 
				
			
			}
			
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				pro = progress;
			
				mSeekTv.setText(progress + " / " + book.getTotalpage() + "페이지"); 
				
				
				Log.d("why", pro+"");	
				//독서시작일 
				if(startdate.getText().toString().isEmpty() && progress!=0){
					new DatePickerDialog(BookMarkActivity.this, mDateSetListener, mYear, mMonth, mDay).show();
				}
				
				//독서완료일 관련
				if ((book.getTotalpage()-progress)!=0){
					mProgressTv.setText("완독까지 "+(book.getTotalpage()-progress)+" 페이지 남았습니다.");
				}else{
					mProgressTv.setText("독서완료. 축하축하!");
					Log.d("here", progress+" " + book.getEnddate()+" "+ enddate.getText().toString());
					pangimg = (LinearLayout) findViewById(R.id.bookmark_pangimglinear);
					pangimg.setVisibility(LinearLayout.VISIBLE);
					if(enddate.getText().toString().isEmpty()){
						new DatePickerDialog(BookMarkActivity.this, mDateSetListener2, mYear, mMonth, mDay).show();
					}
				}
			}
		});
		
	}//onCreate
	
	
	private void calendar(){
		
		Calendar cal = new GregorianCalendar();
		mYear = cal.get(Calendar.YEAR);
		mMonth = cal.get(Calendar.MONTH);
		mDay = cal.get(Calendar.DAY_OF_MONTH);
		
	}
	
	 DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
				mYear = year;
				mMonth = monthOfYear;
				mDay = dayOfMonth;
				
				setDate = String.format("%d/%02d/%d", mYear, mMonth+1, mDay);
				startdate.setText(setDate);
				
			}
		};//DatePickerDialog
	
		 DatePickerDialog.OnDateSetListener mDateSetListener2 = new DatePickerDialog.OnDateSetListener() {
				@Override
				public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
					mYear = year;
					mMonth = monthOfYear;
					mDay = dayOfMonth;
					
					setDate = String.format("%d/%02d/%d", mYear, mMonth+1, mDay);
					enddate.setText(setDate);
					
				}
			};//DatePickerDialog

	void cursorStart(Cursor c){
		
		startManagingCursor(c);
		while (c.moveToNext()) {
			mId = c.getInt(c.getColumnIndex("_id")); 
			mName = c.getString(c.getColumnIndex("name"));
			mAuthor = c.getString(c.getColumnIndex("author"));
			mPublisher = c.getString(c.getColumnIndex("publisher"));
			mBookimg = c.getString(c.getColumnIndex("bookimg"));
			mImgtype = c.getInt(c.getColumnIndex("imgtype"));
			mStatus = c.getInt(c.getColumnIndex("status"));
			mTotalpage = c.getInt(c.getColumnIndex("totalpage"));
			mCurrentpage = c.getInt(c.getColumnIndex("currentpage"));
			mStartdate = c.getString(c.getColumnIndex("startdate"));
			mEnddate = c.getString(c.getColumnIndex("enddate"));
			
		}
		
	}
	
	@Override
		protected void onPause() { //책갈피 페이지 저장!!
			super.onPause();
			Log.d("TEST", "MARK - onPause()");
			
			//시크바 현재값 currentpage에 update
			if (book.getCurrentpage()==0){ //처음. 0일때 
				Log.d("why", enddate.getText().toString().trim()+"  1번:" +pro + " " + book.getCurrentpage());
				ContentValues updateRowValues = new ContentValues();
				
				if(startdate.getText().toString().isEmpty()){
					updateRowValues.put("currentpage", pro);
					String whereClause="_id=?";
					String[] whereArgs = new String[1];
					whereArgs[0] = Integer.toString(book.getId());
					mBookMgr.updateBook(updateRowValues, whereClause, whereArgs);
					Log.d("why", enddate.getText().toString().trim()+"  1번의 1:" +pro + " " + book.getCurrentpage());
				}else if(!startdate.getText().toString().isEmpty() && enddate.getText().toString().isEmpty()){
					updateRowValues.put("currentpage", pro);
					updateRowValues.put("startdate", startdate.getText().toString());
					updateRowValues.put("status", 2);
					String whereClause="_id=?";
					String[] whereArgs = new String[1];
					whereArgs[0] = Integer.toString(book.getId());
					mBookMgr.updateBook(updateRowValues, whereClause, whereArgs);
					Log.d("why", enddate.getText().toString().trim()+"  1번의 2:" +pro + " " + book.getCurrentpage());
				}else {
					updateRowValues.put("currentpage", pro);
					updateRowValues.put("startdate", startdate.getText().toString());
					updateRowValues.put("enddate", enddate.getText().toString());
					updateRowValues.put("status", 3);
					String whereClause="_id=?";
					String[] whereArgs = new String[1];
					whereArgs[0] = Integer.toString(book.getId());
					mBookMgr.updateBook(updateRowValues, whereClause, whereArgs);
					Log.d("why", enddate.getText().toString().trim()+"  1번의 3:" +pro + " " + book.getCurrentpage());
				}//inner if~else
				
			}else if(pro==0){//변동사항없을때
				Log.d("why", enddate.getText().toString().trim()+"  2번:" +pro + " " + mCurrentpage +" "+ book.getCurrentpage());
				ContentValues updateRowValues = new ContentValues();
				updateRowValues.put("currentpage", book.getCurrentpage());
				String whereClause="_id=?";
				String[] whereArgs = new String[1];
				whereArgs[0] = Integer.toString(book.getId());
				
				mBookMgr.updateBook(updateRowValues, whereClause, whereArgs);
				
			}else if(pro!=book.getCurrentpage() && pro==book.getTotalpage()){ //책완독시 상태변경, 독서완료일 변경 
			
				ContentValues updateRowValues = new ContentValues();
				Log.d("why", enddate.getText().toString().trim()+"  5번:" +pro + " " + book.getCurrentpage());
				
				updateRowValues.put("currentpage", pro);
				updateRowValues.put("status", 3);
				updateRowValues.put("enddate", enddate.getText().toString().trim());
				//Toast.makeText(BookMarkActivity.this, enddate.getText() + "".toString().trim(), Toast.LENGTH_LONG).show();
				String whereClause="_id=?";
				String[] whereArgs = new String[1];
				whereArgs[0] = Integer.toString(book.getId());
				
				mBookMgr.updateBook(updateRowValues, whereClause, whereArgs);
				
			}else if(pro!=book.getCurrentpage()){ //수정했을 때 !! 못합치겠음....
				Log.d("why", enddate.getText().toString().trim()+"  6번:" +pro + " " + book.getCurrentpage());
				ContentValues updateRowValues = new ContentValues();
				updateRowValues.put("currentpage", pro);
				String whereClause="_id=?";
				String[] whereArgs = new String[1];
				whereArgs[0] = Integer.toString(book.getId());
				
				mBookMgr.updateBook(updateRowValues, whereClause, whereArgs);
			}//if~else
			
		}//onPause
	
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.bookmark_actionbarmenu, menu);
		return super.onCreateOptionsMenu(menu); 
	}
	

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent =null;
		switch(item.getItemId()){
			
		case R.id.memo_icon: //메모
			
			intent = new Intent(BookMarkActivity.this, BookMemoActivity.class);
			intent.putExtra("BOOK", book);
			Log.d("book1", book.getAuthor() +"메모부분");
			//intent.putExtras(extra);
			startActivity(intent); 
			break;
			
		case android.R.id.home:
			  intent = new Intent(this, BookListActivity.class); 
			  intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //액티비티 쌓이지 않기위해. 바로메인
			  startActivity(intent);
			break;
			
		}
		return super.onOptionsItemSelected(item);
	}
	
	
}
